package buildervalidator

import (
	"fmt"
	"yunj/pkg/yunj/util"

	"github.com/worklz/go-validate"
)

type Import struct {
	validate.Validator
}

func (v *Import) DefineRules() map[string]interface{} {
	return map[string]interface{}{
		"builder_id":         "required",
		"builder_async_type": "required|in:import",
		"items":              "required|json",
	}
}

func (v *Import) DefineTitles() map[string]string {
	return map[string]string{
		"builder_id" + ".required":         "访问错误",
		"builder_async_type" + ".required": "builder_async_type" + "参数缺失",
		"builder_async_type" + ".in":       "builder_async_type" + "参数错误",
		"items.required":                   "items参数缺失",
		"items.json":                       "items参数错误",
	}
}

func (v *Import) DefineScenes() map[string][]string {
	return map[string][]string{
		"AsyncRequest": {"builder_id", "builder_async_type", "items"},
	}
}

func (v *Import) HandleDatas(datas map[string]interface{}, scene string) (err error) {
	if scene == "AsyncRequest" {
		typ := datas["builder_async_type"]
		switch typ {
		case "import":
			var items []map[string]any
			items, err = util.JsonTo[[]map[string]any](datas["items"].(string))
			if err != nil {
				err = fmt.Errorf("items参数格式错误！%v", err)
				return
			}
			datas["items"] = items
			datas["count"] = uint(len(items))
		}
	}
	return
}
